package com.nanjia.boot.myflow.order.item.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.common.enums.OrderStatusEnum;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.myflow.order.item.converter.OrderItemConverter;
import com.nanjia.boot.myflow.order.item.mapper.OrderItemMapper;
import com.nanjia.boot.myflow.order.item.model.entity.OrderItem;
import com.nanjia.boot.myflow.order.item.model.form.OrderItemForm;
import com.nanjia.boot.myflow.order.item.model.query.OrderItemQuery;
import com.nanjia.boot.myflow.order.item.model.vo.OrderItemVO;
import com.nanjia.boot.myflow.order.item.service.OrderItemService;
import com.nanjia.boot.myflow.order.mapper.OrderMapper;
import com.nanjia.boot.myflow.order.model.entity.Order;
import com.nanjia.boot.myflow.order.model.form.OrderForm;
import com.nanjia.boot.product.sku.mapper.ProductSkuMapper;
import com.nanjia.boot.product.sku.model.entity.ProductSku;
import com.nanjia.boot.product.sku.spec.value.mapper.SkuSpecValueMapper;
import com.nanjia.boot.product.sku.spec.value.model.entity.SkuSpecValue;
import com.nanjia.boot.product.spec.value.mapper.SpecValueMapper;
import com.nanjia.boot.product.spec.value.model.entity.SpecValue;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 订单商品明细服务实现类
 *
 * @author 周洋
 * @since 2025-07-18 14:59
 */
@Service
@RequiredArgsConstructor
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements OrderItemService {

    private final OrderItemConverter orderItemConverter;


    private final ProductSkuMapper productSkuMapper;

    private final OrderItemMapper orderItemMapper;

    private final SkuSpecValueMapper skuSpecValueMapper;

    private final OrderMapper orderMapper;
    private final SpecValueMapper specValueMapper;


    /**
     * 获取订单商品明细分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<OrderItemVO>} 订单商品明细分页列表
     */
    @Override
    public IPage<OrderItemVO> getOrderItemPage(OrderItemQuery queryParams) {
        Page<OrderItemVO> pageVO = this.baseMapper.getOrderItemPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取订单商品明细表单数据
     *
     * @param id 订单商品明细ID
     * @return 订单商品明细表单数据
     */
    @Override
    public OrderItemForm getOrderItemFormData(Long id) {
        OrderItem entity = this.getById(id);
        return orderItemConverter.toForm(entity);
    }

    /**
     * 新增订单商品明细
     *
     * @param formData 订单商品明细表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveOrderItem(OrderItemForm formData) {
        OrderItem entity = orderItemConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新订单商品明细
     *
     * @param id       订单商品明细ID
     * @param formData 订单商品明细表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateOrderItem(Long id, OrderItemForm formData) {
        OrderItem entity = orderItemConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除订单商品明细
     *
     * @param ids 订单商品明细ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteOrderItems(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的订单商品明细数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Override
    public boolean addItemToCart(OrderItemForm formData, String ipAddr, OrderForm cartOrder) {


        ProductSku productSku = productSkuMapper.selectById(formData.getSkuId());
        if (productSku == null && productSku.getStatus() != StatusEnum.ENABLE.getValue()) {
            return false;
        }

//        if (availableStockCount < formData.getQuantity()) {
//            return false;
//        }


        List<SkuSpecValue> skuSpecValues = skuSpecValueMapper.selectList(new LambdaQueryWrapper<SkuSpecValue>().eq(SkuSpecValue::getSkuId, productSku.getId()));

        String skuSpecs = "";
        for (SkuSpecValue skuSpecValue : skuSpecValues) {
            skuSpecs = skuSpecs + skuSpecValue.getSpecValueId() + ";";
        }
        Order order = new Order();
        order.setId(formData.getOrderId());
        order.setTotalAmount(cartOrder.getTotalAmount().add(productSku.getPrice().multiply(new BigDecimal(formData.getQuantity()))));
        orderMapper.updateById(order);
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, formData.getOrderId()).eq(OrderItem::getSkuId, formData.getSkuId()));


        if (CollectionUtils.isNotEmpty(orderItems)) {
            OrderItem item = orderItems.get(0);
            item.setPrice(productSku.getPrice());
            item.setQuantity(item.getQuantity() + formData.getQuantity());
            item.setProductName(formData.getProductName());
            item.setUpdateIp(ipAddr);
            item.setUpdateTime(LocalDateTime.now());
            item.setSkuSpecs(skuSpecs);
            return this.updateById(item);
        } else {
            OrderItem item = new OrderItem();
            item.setItemCode("MALL" + SecurityUtils.getUser() + new Date().getTime());
            item.setOrderId(formData.getOrderId());
            item.setSkuId(formData.getSkuId());
            item.setProductName(formData.getProductName());
            item.setQuantity(formData.getQuantity());
            item.setUpdateIp(ipAddr);
            item.setUpdateTime(LocalDateTime.now());
            item.setCreateTime(LocalDateTime.now());
            item.setCreateIp(ipAddr);
            item.setCreateBy(SecurityUtils.getUserStrId());
            item.setSkuSpecs(skuSpecs);
            item.setPrice(productSku.getPrice());
            item.setDaf0Id(1L);
            item.setDaf1Id(1L);
            return this.save(item);
        }


    }

    @Override
    public List<OrderItemVO> getOrderItemList(OrderItemQuery queryParams) {
        if (queryParams.getOrderId() == null) {
            queryParams.setUserId(SecurityUtils.getUserId());
            queryParams.setOrderStatus(OrderStatusEnum.CART.getValue());
        }
        List<OrderItemVO> orderItemList = orderItemMapper.getOrderItemList(queryParams);
        if (CollectionUtils.isEmpty(orderItemList)) {
            return orderItemList;
        }

        // 提取所有需要的 specIds
        Set<String> allSpecIds = new HashSet<>();
        for (OrderItemVO orderItemVO : orderItemList) {
            String skuSpecs = orderItemVO.getSkuSpecs();
            String[] specIds = skuSpecs.split(";");
            allSpecIds.addAll(Arrays.asList(specIds));
        }
        // 批量查询所有 SpecValue
        List<SpecValue> specValues = specValueMapper.selectBatchIds(new ArrayList<>(allSpecIds));
        // 将查询结果存入 Map，SpecValue ID 作为键
        Map<Long, SpecValue> specValueMap = specValues.stream().collect(Collectors.toMap(SpecValue::getId, Function.identity()));

        // 处理每个订单项
        for (OrderItemVO orderItemVO : orderItemList) {
            String skuSpecs = orderItemVO.getSkuSpecs();
            String[] specIds = skuSpecs.split(";");

            // 查询规格值并拼接成字符串
            String specValueString = Arrays.stream(specIds)
                    .map(specId -> {
                        SpecValue specValue = specValueMap.get(Long.valueOf(specId));
                        return specValue != null ? specValue.getValueName() : "";
                    })
                    .collect(Collectors.joining(";"));

            orderItemVO.setSpecValues(specValueString);
        }


        return orderItemList;
    }

    @Override
    public List<OrderItemVO> getOrderItemList(List<Long> orderIds) {

        List<OrderItemVO> orderItemList = orderItemMapper.getOrderItemListByids(orderIds);
        // 提取所有需要的 specIds
        Set<String> allSpecIds = new HashSet<>();
        for (OrderItemVO orderItemVO : orderItemList) {
            String skuSpecs = orderItemVO.getSkuSpecs();
            String[] specIds = skuSpecs.split(";");
            allSpecIds.addAll(Arrays.asList(specIds));
        }
        if (CollectionUtils.isNotEmpty(allSpecIds)) {
            // 批量查询所有 SpecValue
            List<SpecValue> specValues = specValueMapper.selectBatchIds(new ArrayList<>(allSpecIds));

            // 将查询结果存入 Map，SpecValue ID 作为键
            Map<Long, SpecValue> specValueMap = specValues.stream().collect(Collectors.toMap(SpecValue::getId, Function.identity()));
            // 处理每个订单项
            for (OrderItemVO orderItemVO : orderItemList) {
                String skuSpecs = orderItemVO.getSkuSpecs();
                String[] specIds = skuSpecs.split(";");

                // 查询规格值并拼接成字符串
                String specValueString = Arrays.stream(specIds)
                        .map(specId -> {
                            SpecValue specValue = specValueMap.get(Long.valueOf(specId));
                            return specValue != null ? specValue.getValueName() : "";
                        })
                        .collect(Collectors.joining(";"));

                orderItemVO.setSpecValues(specValueString);
            }
        }





        return orderItemList;
    }

    @Override
    public Integer insertBatch(List<OrderItem> insertOrderItemList) {
        return orderItemMapper.insertBatch(insertOrderItemList);
    }

    @Override
    public Boolean updateOrderItems(List<OrderItem> orderItemList) {
        return this.updateBatchById(orderItemList, orderItemList.size());
    }

    @Override
    public List<OrderItem> selectOrderItemsByOrderId(Long orderId) {
        return this.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderId).orderByDesc(OrderItem::getId));
    }
}
